<?php

namespace app\models;

use yii\db\ActiveRecord;

/**
 * 代理商宣传信息
 * Class AgentPublish
 * @package app\models
 *
 * @property integer $id PK
 * @property integer $agent_id 代理商编号
 * @property string $name 名称
 * @property integer $type 类型
 * @property string $value 内容
 * @property integer $sort 排序
 */
class AgentPublish extends ActiveRecord
{
    const TYPE_TEXT = 1;
    const TYPE_MULTI_TEXT = 2;
    const TYPE_RICH_TEXT = 3;
    const TYPE_FILE = 4;
    const TYPE_IMAGE = 5;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name', 'type', 'value'], 'required'],
            ['name', 'string', 'max' => 32],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'name' => '名称',
            'type' => '类型',
            'value' => '内容',
        ];
    }

    /**
     * @inheritdoc
     */
    public function beforeSave($insert)
    {
        if ($insert) {
            $this->sort = AgentPublish::find()->andWhere(['agent_id' => $this->agent_id])->count();
        }
        return parent::beforeSave($insert);
    }

    /**
     * @inheritdoc
     */
    public function afterDelete()
    {
        /** @var AgentPublish $sortPublish */
        foreach (AgentPublish::find()
                     ->andWhere(['agent_id' => $this->agent_id])
                     ->andWhere(['>', 'sort', $this->id])
                     ->each() as $sortPublish) {
            $sortPublish->updateCounters(['sort' => -1]);
        }
        parent::afterDelete();
    }
}
